package utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zjh
 */
public class RegexUtil {

    /**
     * 将source字符串替换${}格式的字符
     *
     * @param source        源字符串
     * @param msgParam      参数，json（消息）
     * @param metadataParam 参数，map（元数据）
     * @return 替换后的字符串，如果不包含指定格式，则返回源字符串
     */
    public static String regexString(String source, String msgParam, Map<String, Object> metadataParam) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        //正则--${xxx}
        String s = "\\$\\{([^}]*)}";
        Pattern regex = Pattern.compile(s);

        Matcher matcher = regex.matcher(source);
        if (matcher.find()) {
            //匹配到正则，重置
            matcher.reset();
            while (matcher.find()) {
                String old = matcher.group();
                String[] keys = matcher.group(1).split("\\.");
                switch (keys[0]) {
                    case "msg":
                        source = regex(source, old, keys, JSONObject.parseObject(msgParam));
                        break;
                    case "metadata":
                        source = regex(source, old, keys, new JSONObject(metadataParam));
                        break;
                    default:
                        System.out.println("未识别" + keys[0] + "前缀，现只能为msg或metadata");
                        break;
                }

            }
        }
        return source;
    }

    private static String regex(String source, String old, String[] keys, JSONObject param) {
        String news = "";
        for (int i = 1; i < keys.length; i++) {
            String key = keys[i];
            if (i == keys.length - 1) {
                news = param.getString(key);
            } else {
                param = param.getJSONObject(key);
            }
        }
        if (StringUtils.isNotEmpty(news)) {
            source = source.replace(old, news);
        }
        return source;
    }
}
